/*
 * Copyright 2009 Thor Hovden
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *     http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the
 * License. 
 */
package eviva.adapters;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import eviva.exceptions.Showstopper;
import eviva.structure.MissionControl;

/**
 * Represents a file and provides helpful methods to handle it
 * 
 * @author Thor Hovden
 */
public class File {
	java.io.File file;
	MissionControl mission;

	/**
	 * Construct a file
	 * 
	 * @param context
	 * @param filename
	 * @throws Showstopper
	 */
	public File(MissionControl mission, String filename) throws Showstopper {
		this.mission = mission;
		MissionControl.Mission m3 = mission.set(3, "Represent a file");

		if (filename == null) {
			String message = "Null filename given";
			mission.abort(m3, message);
			throw new Showstopper(message);
		}
		this.file = new java.io.File(filename);
		if (!this.file.canRead()) {
			String message = "Missing read access for " + filename;
			mission.abort(m3, message);
			throw new Showstopper(message);
		}

		mission.complete(m3);
	}

	/**
	 * Read file contents into a String
	 * 
	 * @param context
	 * @return String with file contents
	 * @throws Showstopper
	 */
	public String read() throws Showstopper {
		MissionControl.Mission m3 = mission.set(3, "Open file");
		FileReader fr;
		try {
			fr = new FileReader(this.file);
		} catch (FileNotFoundException e) {
			mission.abort(m3, e.getMessage());
			throw new Showstopper(e.getMessage());
		}
		mission.complete(m3);

		m3 = mission.set(3, "Read file");
		final int FAST_BLOCKSIZE = 8192;// not knowing, only assuming
		char[] cbuf = new char[FAST_BLOCKSIZE];
		StringBuffer buf = new StringBuffer();
		int n;
		try {
			while ((n = fr.read(cbuf)) > 0) {
				buf.append(cbuf, 0, n);
			}
		} catch (IOException e) {
			String message = "Cannot read " + this.file.getAbsolutePath() + ", exception caught: "
					+ e.getMessage();
			mission.abort(m3, message);
			throw new Showstopper(message);
		}
		mission.complete(m3);

		return buf.toString();
	}
}
